package com.sayyi.validate.constraints.custom;

import com.sayyi.validate.valid.ValidateMapCache;
import org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorContext;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Map;

/**
 * @author xuchuang
 * date 2021/12/7 2:36 PM
 */
public class NotExistValidator implements ConstraintValidator<NotExist, Object> {

    private String setKey;
    private String messageTemplate;
    @Override
    public void initialize(NotExist constraintAnnotation) {
        setKey = constraintAnnotation.value();
        messageTemplate = constraintAnnotation.message();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        Map<Object, Object> sets = ValidateMapCache.get(setKey);
        if (sets == null) {
            return true;
        }
        HibernateConstraintValidatorContext hibernateContext = context.unwrap(
                HibernateConstraintValidatorContext.class );

        boolean valid = !sets.containsKey(value);
        if (!valid){
            hibernateContext.disableDefaultConstraintViolation();
            hibernateContext.addExpressionVariable("cachedValue", sets.get(value));
            context.buildConstraintViolationWithTemplate(messageTemplate)
                    .addConstraintViolation();
        }
        return valid;
    }

}
